package com.ssy.lingxi.member.merchant.handler.validator;

import com.ssy.lingxi.member.merchant.handler.annotation.PasswordAnnotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author 万宁
 * @version 2.0.0
 * @date 2020-06-19
 */
public class PasswordValidator implements ConstraintValidator<PasswordAnnotation,String> {
    private boolean required;
    private int min;
    private int max;
    private boolean containUpperCase;
    private boolean containLowerCase;
    private boolean containNumbers;
    private boolean containChars;

    @Override
    public void initialize(PasswordAnnotation constraintAnnotation) {
        required = constraintAnnotation.required();
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
        containUpperCase = constraintAnnotation.upperCase();
        containLowerCase = constraintAnnotation.lowerCase();
        containNumbers = constraintAnnotation.numbers();
        containChars = constraintAnnotation.chars();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(!required) {
            return true;
        }

        if (value == null || value.length() < min || value.length() > max) {
            return false;
        }

        int upperCase = 0;
        int lowerCase = 0;
        int number = 0;
        int other = 0;
        for(char c: value.toCharArray()) {
            if (c>='a' && c<='z') {
                lowerCase++;
            } else if (c>='A' && c<='Z') {
                upperCase++;
            } else if (c>='0' && c<='9') {
                number++;
            } else {
                other++;
            }
        }

        if(containUpperCase && upperCase == 0) {
            return false;
        }

        if(containLowerCase && lowerCase == 0) {
            return false;
        }

        if(containNumbers && number == 0) {
            return false;
        }

        return !containChars || other != 0;
    }
}
